import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

//导入axios
import axios from "axios";
import VueAxios from "vue-axios";

// //统一的跨域前缀
// axios.defaults.baseURL = "http://localhost:1688/";
// //设置默认的请求超时时间。例如超过了5s，就会告知用户当前请求超时，请刷新等。
// axios.defaults.timeout = 5000;

//引入ElementUI
import ElementUI from "element-plus";
import "element-plus/dist/index.css";

//改中文
import locale from "element-plus/lib/locale/lang/zh-cn";
//1、引用图标库
import * as ElIcons from "@element-plus/icons-vue";
const app = createApp(App);
app.use(router);
app.use(VueAxios, axios);
app.use(ElementUI, { locale });
app.use(store);
// 屏蔽警告信息
app.config.warnHandler = () => null;
// 全局路由构造函数，判断是否登录和要跳转到页面

router.beforeEach((to, from, next) => {

    if (to.matched.some(m => m.meta.requireAuth)) {
        const token =JSON.parse(sessionStorage.getItem("vuex"));

        // 需要登录
        if(token ){
            next()
        } else if (to.path !== '/login') {

            const token =JSON.parse(sessionStorage.getItem("vuex")).userData.token;
            if (token === 'null' || token === '' || token === undefined){
                next({path: '/login'})
                Toast({ message: '检测到您还未登录,请登录后操作！', duration: 1500 })
            }
        } else {
            next()
        }
    } else {   // 不需要登录
        next()
    }
})

//2、先加载图标库
for (const [key, comp] of Object.entries(ElIcons)) {
  app.component(key, comp);
}
// 配置公共url
//添加请求拦截器
axios.interceptors.request.use(
    config =>{
       if (JSON.parse(sessionStorage.getItem("vuex"))!=null){

           const token =JSON.parse(sessionStorage.getItem("vuex")).userData.token;
           if(token){
               console.log(token,"fff")
               // config.headers.common['token'] =token
               config.headers.token =token;
           }
       }

      return config;
    },
    error =>{
      //对请求错误做什么
        console.log("1fff")
      return Promise.reject(error);
    })

app.mount("#app");
